package com.authine.cloudpivot.ext.controller;

import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import jdk.nashorn.internal.runtime.regexp.joni.Regex;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.axis.utils.StringUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.transform.Transformers;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author hxd
 * @Date 2022/2/7 14:03
 * @Description 课程中心
 **/
@Slf4j
@RestController
@RequestMapping("/api/course")
public class CourseController extends BaseController {
    @PersistenceContext
    EntityManager entityManager;

    @PostMapping("list")
    public Map<String, Object> list(Map<String, Object> map) {
        log.info("\n ==========map:{}", JSON.toJSONString(map));

        StringBuilder countSql = new StringBuilder("SELECT count(*) as count from ix43f_kcqd as a ");

        Query query = entityManager.createNativeQuery(countSql.toString());

        StringBuilder whereStr = new StringBuilder("where 1=1 ");

        //主开发人
        if (map.containsKey("kczkfrtxt")) {
            whereStr.append(" and a.kczkfrtxt like '").append(MapUtils.getString(map, "kczkfrtxt")).append("%'");
        }
        //入库时间
        if (map.containsKey("rksjStart")) {
            whereStr.append(" and a.createdTime > '").append(MapUtils.getString(map, "rksjStart")).append("'");
        }
        //入库时间
        if (map.containsKey("rksjEnd")) {
            whereStr.append(" and a.createdTime < '").append(MapUtils.getString(map, "rksjEnd")).append("'");
        }
        //课程分类
        if (map.containsKey("category")) {
            whereStr.append(" and a.category ='").append(MapUtils.getString(map, "category")).append("'");
        }
        //关键词
        if (map.containsKey("keywords")) {
            String keywords = MapUtils.getString(map, "keywords");
            whereStr.append(" or a.courseName like '%").append(keywords).append("'%");
            whereStr.append(" or a.kcbh like '%").append(keywords).append("'%");
        }

        countSql.append(whereStr);

        BigInteger count = (BigInteger) query.getSingleResult();

        Map<String, Object> rst = new HashMap<>();

        if (count.intValue() == 0) {
            return null;
        }

        StringBuilder listSql = new StringBuilder("SELECT a.id,a.courseName,a.category,a.kczkfrtxt,a.psjb,a.xxrc,a.dzs,if(b.courseId,true,false) as sfydz ")
                .append("from ix43f_kcqd as a  LEFT JOIN (select courseId from ix43f_liked where creater ='")
                .append(super.getUserId()).append("') as  b on a.id = b.courseId ");

        listSql.append(whereStr);

        Integer page = MapUtils.getInteger(map, "page", 0);
        Integer size = MapUtils.getInteger(map, "size", 20);

        if (page > 0) {
            page = page * size;
            size = page + size;
        }

        listSql.append(" limit ").append(page).append(",").append(size);


        List<Map<String, Object>> resultList = entityManager.createNativeQuery(listSql.toString()).unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();

        rst.put("total", count.intValue());
        rst.put("data", resultList);


        return rst;
    }

    /**
     * 获取提问
     */
    @PostMapping("/getquestions")
    public Map<String, Object> getQuestions(@RequestBody Map<String, Object> map) {
        log.info("获取参数，map{}", map);
        String objId = (String) map.get("objId");
        StringBuilder countSql = new StringBuilder("SELECT count(*) as count from iwrwy_myAsk  ");

        Query query = entityManager.createNativeQuery(countSql.toString());

        BigInteger count = (BigInteger) query.getSingleResult();

        Map<String, Object> rst = new HashMap<>();

        if (count.intValue() == 0) {
            return null;
        }
        ArrayList rstlist = new ArrayList<>();

        StringBuilder listSql = new StringBuilder("SELECT a.id id,a.kcqd kcqd,a.ask ask,a.createdTime createdtime,b.name username FROM iwrwy_myAsk a LEFT JOIN h_org_user b on a.creater=b.id where kcqd='")
                .append(objId).append("'");
        List<Map<String, Object>> resultList = entityManager.createNativeQuery(listSql.toString()).unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        for (Map<String, Object> result : resultList) {
            HashMap<Object, Object> map2 = new LinkedHashMap<>();
            String id = (String) result.get("id");
            String ask = (String) result.get("ask");
            Object createdtime = result.get("createdtime");
            Object username = result.get("username");
            map2.put("id", id);
            map2.put("date", createdtime);
            map2.put("content", ask);
            map2.put("username", username);

            //获取提问的回复
            StringBuilder hfSql = new StringBuilder("SELECT a.id id,a.hfnr hfnr,a.createdTime createdtime,b.name username FROM iwrwy_myReply a LEFT JOIN h_org_user b on a.creater=b.id where twid ='")
                    .append(id).append("'");
            List<Map<String, Object>> hflist = entityManager.createNativeQuery(hfSql.toString()).unwrap(NativeQueryImpl.class)
                    .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            ArrayList list1 = new ArrayList<>();
            for (Map<String, Object> m : hflist) {
                Map<Object, Object> children = new LinkedHashMap<>();
                Object id1 = m.get("id");
                Object hfnr = m.get("hfnr");
                Object createdtime1 = m.get("createdtime");
                Object username1 = m.get("username");
                children.put("id", id1);
                children.put("date", createdtime1);
                children.put("content", hfnr);
                children.put("username", username1);
                list1.add(children);
            }

            map2.put("children", list1);
            rstlist.add(map2);
        }
        Integer page = MapUtils.getInteger(map, "page", 0);
        Integer size = MapUtils.getInteger(map, "size", 20);

        if (page > 0) {
            page = page * size;
            size = page + size;
        }

        listSql.append(" limit ").append(page).append(",").append(size);


        rst.put("total", count.intValue());
        rst.put("data", rstlist);


        return rst;
    }

    /**
     * 回复信息
     */
    @PostMapping("/replyquestions")
    @Transactional
    public ResponseResult replyQuestions(@RequestBody Map<String, String> map) {
        log.info("获取参数，map{}", map);
        String twid = map.get("twid");
        String hfnr = map.get("hfnr");
        if (StringUtil.isEmpty(twid)) {
            return getErrResponseResult(500L, "参数为空");
        }
        if (StringUtil.isEmpty(hfnr)) {
            return getErrResponseResult(500L, "回复内容不能为空");
        }
        String userId = getUserId();
        BizObjectCreatedModel bizObjectCreatedModel = new BizObjectCreatedModel();
        bizObjectCreatedModel.setSchemaCode("myReply");
        bizObjectCreatedModel.put("twid", twid);
        bizObjectCreatedModel.put("hfnr", hfnr);
        String bizId = getBizObjectFacade().saveBizObject(userId, bizObjectCreatedModel, false);
        if (StringUtil.isEmpty(bizId)) {
            return getErrResponseResult(500L, "回复失败");
        }
        return getOkResponseResult("回复成功");
    }

    /**
     * 回复流程问题
     */
    @GetMapping("/requestion")
    public ResponseResult requestion(String objectId) {
        log.info("获取参数，objectId{}", objectId);
        if (StringUtil.isEmpty(objectId)) {
            return getErrResponseResult(500L, "参数为空");
        }
        BizObjectCreatedModel askBiz = getBizObjectFacade().getBizObject("myAsk", objectId);
        BizObjectCreatedModel bizObjectCreatedModel = new BizObjectCreatedModel();
        bizObjectCreatedModel.setSchemaCode("myReply");
        bizObjectCreatedModel.put("twid", objectId);
        bizObjectCreatedModel.put("hfnr", askBiz.get("answer"));
        getBizObjectFacade().saveBizObject(askBiz.getModifier().getId(), bizObjectCreatedModel, false);
        return getOkResponseResult("回复成功");
    }

    /**
     * 提问
     */
    @PostMapping("/putquestions")
    public ResponseResult putQuestions(@RequestBody Map<String, Object> map) {
        if (map.isEmpty()) {
            return getErrResponseResult(500L, "参数为空");
        }
        String userId = getUserId();
        UserModel user = getOrganizationFacade().getUser(userId);
        BizObjectCreatedModel bizObjectCreatedModel = new BizObjectCreatedModel();
        bizObjectCreatedModel.setSchemaCode("myAsk");
        String kcid = (String) map.get("kcid");
        bizObjectCreatedModel.put("kcqd", kcid);
        bizObjectCreatedModel.put("ask", map.get("question"));
        StringBuilder sql = new StringBuilder();
        sql.append("select kczkfr from iwrwy_kcqd  where id ='").append(kcid).append("'");
        List<Map<String, Object>> resultList = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        bizObjectCreatedModel.put("zkfr", resultList.get(0).get("kczkfr"));
        String bizId = getBizObjectFacade().saveBizObject(userId, bizObjectCreatedModel, false);
        String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "myAskFlow", bizId, true);
        if (StringUtil.isEmpty(bizId) || StringUtil.isEmpty(instanceId)) {
            return getErrResponseResult(500L, "提问失败");
        }
        return getOkResponseResult("提问成功");
    }

    /**
     * 学习推送发布
     */
    @PostMapping("/learnpush")
    public ResponseResult learningPushPub(@RequestBody List<Map<String, Object>> map) {
        log.info("获取参数,map:{}", map);
        if (map.isEmpty()) {
            return getErrResponseResult(500L, "参数为空");
        }
        for (Map m : map) {
            String objId = (String) m.get("objId");

            BizObjectCreatedModel bizObj = new BizObjectCreatedModel("xxtsgl", new HashMap<>(), false);
            bizObj.setId(objId);
            bizObj.put("zt", "已启动");
            getBizObjectFacade().saveBizObject(getUserId(), bizObj, false);
        }
        return getOkResponseResult("发布成功");
    }

    /**
     * 获取学习推送
     */
    @GetMapping("/getlearnpush")
    public ResponseResult getLearnPush(String id, String bmid) {
        if (StringUtil.isEmpty(id) || StringUtil.isEmpty(bmid)) {
            return getErrResponseResult(500L, "参数不能为空");
        }
        StringBuilder sql = new StringBuilder("SELECT kcid FROM `iwrwy_tsxx` where (hhxr like ");
        sql.append("'%").append(id).append("%'").
                append(" or hhxr like ").append("'%").append(bmid).append("%')")
                .append(" and zt=true");
        List<Map<String, Object>> sqllist = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map m : sqllist) {
            String objId = (String) m.get("kcid");
            BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("kcqd", objId);
            Map<String, Object> data = bizObject.getData();
            result.add(data);
        }

        return getOkResponseResult(result, "查询数据成功");
    }

    /**
     * 学习推送取消启动
     */
    @PostMapping("/cancelstart")
    @Transactional
    public ResponseResult cancelStart(@RequestBody List<Map<String, String>> map) {
        if (map.isEmpty()) {
            return getErrResponseResult(500L, "参数为空");
        }
        for (Map<String, String> m : map) {
            String objId = m.get("objId");
            StringBuilder xxtjglupdatesql = new StringBuilder("update iwrwy_xxtsgl set zt='已取消' where id='")
                    .append(objId).append("'");
            entityManager.createNativeQuery(xxtjglupdatesql.toString()).executeUpdate();

        }

        return getOkResponseResult("取消启动成功");
    }

    /**
     * 入库课程启用停用
     */
    @PostMapping("/updateCourseStatus")
    @Transactional
    public ResponseResult updateCourseStatus(@RequestBody Map<String,Object> map) {
        if (map.isEmpty()) {
            return getErrResponseResult(500L, "参数为空");
        }
        List<String> idList = (List<String>) map.get("idList");
        boolean status = (Boolean) map.get("status");
        String s = "已启用";
        for (String objId: idList) {
        if (!status) {
                s = "已停用";
        }
        StringBuilder xxtjglupdatesql = new StringBuilder("update iwrwy_kcqd set kczt='").append(s).append("' where id='")
                    .append(objId).append("'");
        entityManager.createNativeQuery(xxtjglupdatesql.toString()).executeUpdate();
        }
        return getOkResponseResult("修改成功");
    }

    /**
     * 将公司通知ZCGL_TZTG_SUB模型下的
     * 表单公司通知ZCGL_TZTG_SUB的数据项 isRead 改变
     *
     * @param type
     * @return com.authine.cloudpivot.web.api.view.ResponseResult
     * @throws
     */
    @GetMapping("/updateIsReadFromGSTZ")
    @Transactional
    public void updateIsReadFromGSTZ(@RequestParam String objectId, @RequestParam String type) {
        BizObjectFacade bizObjectFacade = getBizObjectFacade();
        String tableName = bizObjectFacade.getTableName("ZCGL_TZTG_SUB");
        StringBuilder xxtjglupdatesql = new StringBuilder("update " + tableName + " set isRead='").append(type).append("' where id='")
                .append(objectId).append("'");
        entityManager.createNativeQuery(xxtjglupdatesql.toString()).executeUpdate();
    }

}
